<?php

namespace App\Http\Controllers\Admin\Site\Recommend;

use App\B2BProject\Admin\AdminControllerBuildTrait;
use App\B2BProject\Custom\MerchantRecommend;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class MerchantController extends Controller
{
    use AdminControllerBuildTrait;

    /**商家推荐
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {

            $query = MerchantRecommend::orderBy('created_at', 'desc');
            if ($merchant_name = $request->query('username')) {
                $query = $query->where('name', 'like', "%$merchant_name%");
            }

            $merchants = $query->paginate($request->query('pageSize', 7));

            $data = [];
            foreach ($merchants as $merchant) {
                $item   = [
                    'id'       => $merchant->id,
                    'name'     => $merchant->name,
                    'img_url' => $merchant->logo,      //TODO 分类是假数据
                    'sort'     => $merchant->sort,
                    'column'   => $merchant->column == 1?'热门企业':'招商加盟',
                    'edit_url' => route('admin.merchant.edit', [$merchant->id, 'page' => $request->input('page')]),
                    'del_url'  => route('admin.merchant.destroy',
                        [$merchant->id, 'page' => $request->input('page')]),
                ];
                $data[] = $item;
            }

            return response()->json([
                'data'           => $data,
                'pagingConfData' => [
                    'page'     => $merchants->currentPage(),
                    'pageSize' => $request->query('pageSize'),
                    'total'    => $merchants->total(),
                ],
            ]);
        }
        return view('admin/site/recommend/index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin/site/recommend/edit/merchant')->with('form', route('admin.merchant.index'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make(
            $request->except(['_token']),
            [
                'name'        => 'required',
                'addr'        => 'required',
                'column'      => 'required',
                'description' => 'required',
                'sort'        => 'required|numeric',
            ]
        );
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator);
        }
        $data = $request->only(['name', 'sort', 'addr', 'column', 'description']);// 只取这些数据
        if ($request->hasFile('logo')) {
            $file         = $request->file('logo');
            $file_name    = Str::random(8) . '.' . $file->getClientOriginalExtension();
            $target       = $file->move(base_path('public/data/upload/recommends'), $file_name);
            $target       = str_replace(base_path('public'), '', $target);
            $data['logo'] = $target;
        }

        $merchants = new MerchantRecommend();
        $merchants->create($data);
        return $this->index($request);
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        $merchant = MerchantRecommend::findOrNew($id);

        return view('admin/site/recommend/edit/merchant')->with('merchant', $merchant)->with('form',
            route('admin.merchant.update', [$merchant->id, 'page' => $request->input('page')]));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make(
            $request->except(['_token']),
            [
                'name'        => 'required',
                'addr'        => 'required',
                'column'      => 'required',
                'description' => 'required',
                'sort'        => 'required|numeric',
            ]
        );
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator);
        }
        $data = $request->only(['name', 'sort', 'addr', 'column', 'description']);// 只取这些数据
        if ($request->hasFile('logo')) {
            $file         = $request->file('logo');
            $file_name    = Str::random(8) . '.' . $file->getClientOriginalExtension();
            $target       = $file->move(base_path('public/data/upload/recommends'), $file_name);
            $target       = str_replace(base_path('public'), '', $target);
            $data['logo'] = $target;
        }
        $merchants = MerchantRecommend::findOrFail($id);
        $merchants->update($data);

        return $this->index($request);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $merchant = MerchantRecommend::findOrFail($id);
        $merchant->delete();
        return $this->index($request);
    }

    /** 批量删除  循环遍历id进行删除
     * @param Request $request
     * @return mixed
     * @throws ModelNotFoundException
     * @throws \Exception
     */
    public function batchRemove(Request $request)
    {
        try {
            return \DB::transaction(function () use ($request) {
                $arr = $request->input('ids');
                foreach ($arr as $merchant_id) {
                    $merchant = MerchantRecommend::findOrFail($merchant_id);
                    $merchant->delete();
                }
                return $this->index($request);
            });
        } catch (ModelNotFoundException $e) {
            throw $e;
        }
    }
}
